package common.servlet;

import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.*;

import javax.ws.rs.Produces;
import javax.ws.rs.core.*;
import javax.ws.rs.ext.*;

import org.json.JSONArray;

/**
 * A reader and writer from string to {@link JSONArray}
 * 
 * @author Gal Lalouche
 */
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class BooleanBodyReaderWriter implements MessageBodyWriter<Boolean>, MessageBodyReader<Boolean> {
	
	@Override
	public long getSize(Boolean arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4) {
		return -1;
	}
	
	@Override
	public boolean isWriteable(Class<?> arg0, Type arg1, Annotation[] arg2, MediaType arg3) {
		return arg0.equals(Boolean.class);
	}
	
	@Override
	public void writeTo(Boolean arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4,
			MultivaluedMap<String, Object> arg5, OutputStream arg6) throws IOException {
		arg6.write(arg0.toString().getBytes());
	}
	
	@Override
	public boolean isReadable(Class<?> arg0, Type arg1, Annotation[] arg2, MediaType arg3) {
		return arg0.equals(Boolean.class);
	}
	
	@Override
	public Boolean readFrom(Class<Boolean> arg0, Type arg1, Annotation[] arg2, MediaType arg3,
			MultivaluedMap<String, String> arg4, InputStream arg5) {
		try (Scanner scanner = new Scanner(arg5)) {
			String str = scanner.useDelimiter("\\A").next();
			if (str == null) {
				throw new IllegalArgumentException("can't parse " + str + " to boolean");
			}
			assert str != null;
			Boolean result = str.equalsIgnoreCase("true") ? true : str.equalsIgnoreCase("false") ? false : null;
			if (result == null) {
				throw new IllegalArgumentException("can't parse " + str + " to boolean");
			}
			return result;
		} catch (NoSuchElementException e) {
			return null;
		}
	}
}
